//
//  SWDownloadOperation.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/20.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
class SWDownloadOperation:Operation
{
    
    private var _task:SWDownloadTask
    var successCallback:(()->Void)?
    var remoteURL:String = ""
    
    init(task:SWDownloadTask)
    {
        _task = task
        remoteURL = task.remoteURL ?? ""
    }
    
    override func main()
    {
        guard let remoteURL = _task.remoteURL,
              let localPath = _task.localPath, remoteURL != "" && localPath != "" else{
            return
        }
        
        let request = WebLoader.buildRequest(remoteURL, data:nil, method:"GET", headers:nil)
        
        var response:URLResponse?
        var loadTimes:Int = 0
        var success:Bool = false
        var data:Data?
        while !success && loadTimes < 3
        {
            loadTimes += 1
            do{
                //URLConnection
                data = try NSURLConnection.sendSynchronousRequest(request, returning: &response)
            }
            catch _{print("load error")}
            
            
            if let response = response as? HTTPURLResponse, response.statusCode == 200,
                let data = data, data.length > 0
            {
                success = true
            }
        }
        
        if let data = data, data.length > 0 && success
        {
            print("下载完成:", data.length, remoteURL)
            
            _task.finished = true
            FileUtility.saveImageCacheToPath(localPath, image:data)
            successCallback?()
            NotificationCenter.default.post(name:NotificationName.DownloadTaskComplete, object: nil, userInfo: [SWKey.remoteURL:remoteURL])
        }
        else
        {
            NotificationCenter.default.post(name:NotificationName.DownloadTaskFail, object: nil, userInfo: [SWKey.remoteURL:remoteURL])
        }
        
        
    }
}
